package week_03;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TreeNodeCodec {
    private List<String> nodeList ;
    private int index = 0;

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        nodeList= new ArrayList<>();
        // 前序遍历
        preTravel(root);
        return String.join(" ", nodeList);
    }

    public void preTravel(TreeNode node) {

        if (node == null) {
            nodeList.add("null");
            return;
        }
        System.out.println(node.val+" "+String.valueOf(node.val));
        nodeList.add(Integer.toString(node.val));
        preTravel(node.left);
        preTravel(node.right);

    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        nodeList = Arrays.asList(data.split(" "));
        index = 0;
        return clac();
    }

    public TreeNode clac() {
        if (nodeList.get(index).equals("null")){
            index ++;
            return null;
        }
        TreeNode root=new TreeNode(Integer.parseInt(nodeList.get(index)));
        index++;
        root.left=clac();
        root.right=clac();
        return root;
    }
}
